package com.heima.example.chat.server.handler;

import com.heima.example.chat.message.LoginRequestMessage;
import com.heima.example.chat.message.LoginResponseMessage;
import com.heima.example.chat.server.service.UserServiceFactory;
import com.heima.example.chat.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author ZhengDp
 * @Date 2023/6/30 21:05
 */
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String userName = msg.getUsername();
        String password = msg.getPassword();
        boolean login = UserServiceFactory.getUserService().login(userName, password);
        LoginResponseMessage res = null;
        if (login) {
            SessionFactory.getSession().bind(ctx.channel(), userName);
            res = new LoginResponseMessage(true, "登录成功");
        } else {
            res = new LoginResponseMessage(false, "用户名或密码不正确");
        }
        ctx.writeAndFlush(res);
    }
}
